package message;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.GregorianCalendar;

public class UDPConnection {

	private String dest_ip;
	private int destPort;
	private DatagramSocket clientSocket;
	private GregorianCalendar last_response;
	public static int MTU = 1024;
	//tempo em segundos
	private static final long TIME_OUT = 10;
	
	public UDPConnection(String dest_ip, int destPort) {
		this.dest_ip = dest_ip;
		this.destPort = destPort;
		this.clientSocket = null;
		last_response = null;
	}
	
	private DatagramSocket getClientSocket() throws SocketException, UnknownHostException {
		if (clientSocket == null) {
			clientSocket = new DatagramSocket();
		}
		return clientSocket;
	}
	
	public void sendMessage(String message) throws IOException {
		byte[] sendData;
		
		sendData = message.getBytes();
		
		if (sendData.length > MTU) {
			throw new IllegalArgumentException("Message is too long!");
		}
			
		DatagramPacket packet = new DatagramPacket(sendData, sendData.length, getDestAddress(), destPort);
		getClientSocket().send(packet);
	}
	
	public void updateLastResponse() {
		last_response = new GregorianCalendar();
	}

	private InetAddress getDestAddress() throws UnknownHostException{
		return InetAddress.getByName(dest_ip);
	}
	
	public boolean checkTimeOut() {
		GregorianCalendar actualDate = new GregorianCalendar();
		return this.last_response == null || (actualDate.getTimeInMillis() - this.last_response.getTimeInMillis())/1000 > TIME_OUT;
	}
}